package com.Spring.SpringSpms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.Spring.SpringSpms.model.Role;

public class RoleDAOImpl implements RoleDAO {
	private JdbcTemplate jdbcTemplate;
	
	
	public RoleDAOImpl(DataSource dataSource)
	{
		this.jdbcTemplate=new JdbcTemplate(dataSource);
	}
	@Override
	public void saveOrUpdate(Role role) {
		// TODO Auto-generated method stub
		if (role.getRoleId() > 0) {
			// update
			String sql = "UPDATE Role SET role_name=?, role_description=? WHERE role_id=?";
			jdbcTemplate.update(sql,role.getRoleName(),role.getRoleDescription(),role.getRoleId());
		} else {
			// insert
			String sql = "INSERT INTO Role (role_name, role_description)"
						+ " VALUES (?, ?)";
			jdbcTemplate.update(sql,role.getRoleName(),role.getRoleDescription());
		}


	}

	@Override
	public void delete(int roleId) {
		// TODO Auto-generated method stub
		String sql = "DELETE FROM Role WHERE role_id=?";
		jdbcTemplate.update(sql,roleId);

	}

	@Override
	public Role get(int roleId) {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM Role WHERE role_id=" + roleId;
		return jdbcTemplate.query(sql, new ResultSetExtractor<Role>() {

			@Override
			public Role extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				if (rs.next()) {
					Role role = new Role();
					role.setRoleId(rs.getInt("role_id"));
					role.setRoleName(rs.getString("role_name"));
					role.setRoleDescription(rs.getString("role_description"));
					return role;
				}
				
				return null;
			}
			
		});
	}
	

	@Override
	public List<Role> list() {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM Role";
		List<Role> listRole = jdbcTemplate.query(sql, new RowMapper<Role>() {

			@Override
			public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
				Role aRole = new Role();
	
				aRole.setRoleId(rs.getInt("role_id"));
				aRole.setRoleName(rs.getString("role_name"));
				aRole.setRoleDescription(rs.getString("role_description"));
				return aRole;
			}
			
		});
		
		return listRole;
	}
	@Override
	public String getRoleName(int roleId) {
		String sql="SELECT role_name FROM role WHERE role_id=?"; 
		
		String name=jdbcTemplate.queryForObject(sql,String.class,roleId);
		return name;
	}

}
